import logging
from typing import Any

from aiogram import types
from aiogram_dialog import DialogManager
from arq import ArqRedis
from fluentogram import TranslatorRunner

from src.presentation.tg_bot.states import ChangeAuthorizationSG

logger = logging.getLogger(__name__)


async def select_ip_address(_, widget: Any, manager: DialogManager):
    manager.dialog_data["authorization_type"] = widget.widget_id
    await manager.switch_to(ChangeAuthorizationSG.select_ip_address)


async def start_changing_authorization_type(
    call: types.CallbackQuery | types.Message,
    _,
    manager: DialogManager,
    allowed_ip_id: int = None,
):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    arqredis: ArqRedis = manager.middleware_data.get("arqredis")
    order_id: int = manager.start_data.get("order_id")
    authorization_type: str = manager.dialog_data.get("authorization_type", "by_password")

    await arqredis.enqueue_job(
        "change_authorization_type_job",
        locale=locale,
        user_id=call.from_user.id,
        order_id=order_id,
        allowed_ip_id=allowed_ip_id,
        authorization_type=authorization_type,
    )

    logger.info(f"Добавлена задача по смене авторизации заказа {order_id}")

    if isinstance(call, types.CallbackQuery):
        await call.message.answer(locale.get("in-work-msg"))
    else:
        await call.answer(locale.get("in-work-msg"))
    await manager.done()


async def start_authorization_change(_, __, manager: DialogManager):
    if manager.start_data:
        order_id: int = manager.start_data.get("order_id")
    else:
        order_id: int = manager.dialog_data.get("order_id")

    await manager.start(ChangeAuthorizationSG.select_authorization_type, {"order_id": order_id})
